<?php

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;

//成功状态
function success($data = '')
{
    $data = array('status' => 200, 'code' => 1);
    return $data;
}
//失败状态
function fail($data = '')
{
    $data = array('status' => 200, 'code' => 0);
    return $data;
}
//程序出错
function error($data = '')
{
    $data = array('status' => 200, 'code' => 0);
    return $data;
}
//验证后台凭证
function verifyBackstageToken($token = "")
{
    if (!isset($token)) {
        $data = array('code' => 4001, 'msg' => '凭证失效，请重新获取');
        return $data;
    }
    if (!Cache::has($token)) {
        $data = array('code' => 4001, 'msg' => '凭证失效，请重新获取');
        return $data;
    }
    $cacheToken = Cache::get($token);
    $cacheToken = str_replace("admin_VXyZ50Dc$^jNvIFt", "", $cacheToken);
    if (empty($cacheToken)) {
        $data = array('code' => 4001, 'msg' => '凭证失效，请重新获取');
        return $data;
    }
    return $cacheToken;
}

//验证凭证
function verifytokens($token = '')
{
    if (!isset($token)) {
        $data = array('code' => 4001, 'msg' => '凭证失效，请重新获取');
        return $data;
    }
    if (!Cache::has($token)) {
        $data = array('code' => 4001, 'msg' => '凭证失效，请重新获取');
        return $data;
    }
    $cacheToken = Cache::get($token);
    $cacheToken = str_replace("reception_VXyZ50Dc$^jNvIFt", "", $cacheToken);
    if (empty($cacheToken)) {
        $data = array('code' => 4001, 'msg' => '凭证失效，请重新获取');
        return $data;
    }
    return $cacheToken;
}
//curlpost请求
function request_post($url = '', $param = '')
{
    if (empty($url) || empty($param)) {
        return false;
    }
    $postUrl = $url;
    $curlPost = $param;
    $curl = curl_init(); //初始化curl
    curl_setopt($curl, CURLOPT_URL, $postUrl); //抓取指定网页
    curl_setopt($curl, CURLOPT_HEADER, 0); //设置header
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); //要求结果为字符串且输出到屏幕上
    curl_setopt($curl, CURLOPT_POST, 1); //post提交方式
    curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
    $data = curl_exec($curl); //运行curl
    curl_close($curl);

    return $data;
}

//curlget请求
function request_get($url = '')
{
    //初始化
    $ch = curl_init();
    //设置选项，包括URL
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    //执行并获取HTML文档内容
    $data = curl_exec($ch);
    //释放curl句柄
    curl_close($ch);
    //打印获得的数据
    return $data;
}

/**
 *  作用：产生随机字符串，不长于32位
 */
function createNoncestr($length = 32)
{
    $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
    $str = "";
    for ($i = 0; $i < $length; $i++) {
        $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
    }
    return $str;
}

//多维数组根据指定字段去重
function array_unset_dr($arr, $key = '')
{
    //建立一个目标数组
    $res = array();
    foreach ($arr as $value) {
        //查看有没有重复项
        if (isset($res[$value[$key]])) {
            unset($value[$key]);  //有：销毁
        } else {
            $res[$value[$key]] = $value;
        }
    }
    $res = array_values($res);
    return $res;
}

//替换危险字符
function replaceSpecialChar($strParam)
{
    $regex = "/\/|\~|\!|\@|\#|\\$|\%|\^|\&|\*|\(|\)|\（|\）|\_|\+|\{|\}|\:|\<|\>|\?|\[|\]|\,|\.|\/|\;|「|」|\'|\`|\-|\=|\\\|\||\s+/";
    return preg_replace($regex, "", $strParam);
}

/*检测是否符合*/
function is_string_regular($str)
{
    $pregs = '/select|insert|update|CR|document|LF|eval|delete|script|alert|\'|\/\*|\#|\--|\ --|\/|\*|\-|\+|\=|\~|\*@|\*!|\$|\%|\^|\&|\(|\)|\/|\/\/|\.\.\/|\.\/|union|into|load_file|outfile/';
    $check = preg_match($pregs, $str);
    if ($check == 1) {
        return false;
    } else {
        return true;
    }
}
// 控制积分增加或减少
function integral($userid = 0, $integral_type = 0, $integral_num = 0, $integral_log = "")
{
    $data['user_id'] = $userid; //用户ID
    $data['integral_type'] = $integral_type; //1增加2减少
    $data['integral_num'] = $integral_num; //增加减少的积分数
    $map['user_id'] = $data['user_id'];
    $info = DB::table('users')->where($map)->first();
    $data['integral'] = $info->integral;
    $data['integral_create_time'] = time();
    $data['integral_log'] = $integral_log;
    $date['integral'] = $info->integral + $integral_num;
    DB::table('user_id')->where($map)->update($date);
    DB::table('user_integral_log')->insert($data);
}


function  arrangement_phone($phone)
{
    if (empty($phone)) {
        return false;
    }
    $result = '';
    for ($i = 0; $i < strlen($phone); $i++) {
        if (is_numeric($phone[$i])) {
            $result .= $phone[$i];
        }
    }
    return $result;
}
//手机号验证
function verification_phone($phone)
{
    if (empty($phone)) {
        return false;
    }
    $verification = '/^(((13[0-9])|(14[57])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|190|197|196|192)[0-9]{8})$/';
    if (!preg_match($verification, arrangement_phone($phone))) {
        return false;
    }
    return true;
}


//获取真实ip
function get_real_ip()
{
    if (getenv('HTTP_CLIENT_IP')) {

        $ip = getenv('HTTP_CLIENT_IP');
    }

    if (getenv('HTTP_X_REAL_IP')) {

        $ip = getenv('HTTP_X_REAL_IP');
    } elseif (getenv('HTTP_X_FORWARDED_FOR')) {

        $ip = getenv('HTTP_X_FORWARDED_FOR');

        $ips = explode(',', $ip);

        $ip = $ips[0];
    } elseif (getenv('REMOTE_ADDR')) {

        $ip = getenv('REMOTE_ADDR');
    } else {

        $ip = '0.0.0.0';
    }
    return $ip;
    // $ip = FALSE;
    // //客户端IP 或 NONE 
    // if (!empty($_SERVER["HTTP_CLIENT_IP"])) {
    //     $ip = $_SERVER["HTTP_CLIENT_IP"];
    // }
    // //多重代理服务器下的客户端真实IP地址（可能伪造）,如果没有使用代理，此字段为空
    // if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
    //     $ips = explode(", ", $_SERVER['HTTP_X_FORWARDED_FOR']);
    //     if ($ip) {
    //         array_unshift($ips, $ip);
    //         $ip = FALSE;
    //     }
    //     for ($i = 0; $i < count($ips); $i++) {
    //         if (!preg_match("^(10│172.16│192.168).", $ips[$i])) {
    //             $ip = $ips[$i];
    //             break;
    //         }
    //     }
    // }
    // //客户端IP 或 (最后一个)代理服务器 IP 
    // return ($ip ? $ip : $_SERVER['REMOTE_ADDR']);
}
// 是否https
function http_type()
{
    //判断是http还是https
    $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? "https://" : "http://";
    return  $http_type;
}
// ----微信模块
function curl_post($url = '', $postdata = '', $options = array())
{
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    if (!empty($options)) {
        curl_setopt_array($ch, $options);
    }
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}
//获取微信接口调用凭证
function getWeiXinAccessToken($APPID = "", $APPSECRET = "")
{
    $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $APPID . "&secret=" . $APPSECRET;
    $res = request_get($url);
    $res = json_decode($res);
    Cache::put('wxAccessToken', $res->access_token);
    return $res->access_token;
}
//获取生成的微信小程序码
function getWeiXinUnlimited($scene = "", $page = "", $ACCESS_TOKEN = "")
{
    $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" . $ACCESS_TOKEN;
    $postdata = [
        "path" => $page,
        "scene" => $scene,
        "width" => 430,
    ];
    $res = curl_post($url, json_encode($postdata), $options = array());
    Storage::disk('local')->put('wxPublic/' . $page . $scene . '.jpg', $res, 'public');
    $url =  Storage::url($page . $scene . '.jpg');
    return $url;
}

//微信内容过滤
function WeiXinmsgSecCheck($content = "", $ACCESS_TOKEN = "")
{
    $url = "https://api.weixin.qq.com/wxa/msg_sec_check?access_token=" . $ACCESS_TOKEN;
    $param = [
        'access_token' => $ACCESS_TOKEN,
        'content' => $content
    ];
    $result = request_post($url, json_encode($param));
    return $result;
}


// ----微信模块